import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import ButtonModel from 'base/models/ButtonModel';
import ButtonWidget from 'widgets/ButtonWidget';
import AddCriterionView from './AddCriterionView';
import BaseCriterionModel from 'statistics/models/criterion/BaseModel'

import CriteriaCollectionView from './CriteriaCollectionView';

const template = require('./templates/EntryFormComponent.mustache');

/*
  Component in charge of the configuration of a statistic entry and its criteria

  Criteria are a tree of criterion

    Some criteria are clauses (AND/OR)
    Other are Surrounding criteria on a related table (One TO many relationship)
    Latest are common (string/number, selectionnable options ...)

*/

const EntryFormComponent = Mn.View.extend({
    template: template,
    regions: {
        editButton: {
            'el': '.edit-btn-container',
            replaceElement: true
        },
        criteria: '.criteria-container',
        popup: '.popup'
    },
    childViewEvents: {
        'edit:entry:click': 'onEditClicked',
        'add:click': "onAddClicked",
        'criterion:delete': 'onCriterionDelete',
    },
    initialize(options) {
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.listenTo(this.facade, 'criterion:added', this.renderList.bind(this));
        console.log(options);
        this.mergeOptions(options, ['criteriaCollection']);
        console.log(this.criteriaCollection);
    },
    onButtonClicked(keyname) {
        if (keyname == 'editentry') {
            this.onEditClicked();
        } else {
            this.onAddClicked(this.getRootCriterion());
        }
    },
    onEditClicked() {
        const app = Radio.channel('app');
        app.trigger('navigate', 'editentry/' + this.model.get('id'));
    },
    getRootCriterion() {
        return this.criteriaCollection.models[0];
    },
    onAddClicked(parentModel) {
        console.log("EntryFormComponent");
        parentModel = parentModel || this.getRootCriterion();
        const model = new BaseCriterionModel({
            parent_id: parentModel.get('id'),
            entry_id: this.model.get('id')
        });
        let parentPath;
        if (parentModel.get('type') === 'onetomany') {
            parentPath = parentModel.get('key');
        }

        const view = new AddCriterionView({
            model: model,
            attributePath: parentModel.collection.path,
            parentPath: parentPath
        })
        this.showChildView('popup', view);
    },
    onCriterionDelete(model) {
        var result = window.confirm("Êtes-vous sûr de vouloir supprimer cet élément ?");
        if (result) {
            model.destroy({
                wait: true,
                success: () => this.criteriaCollection.fetch({
                    reset: true,
                    success: () => this.render()
                })
            });
        }
    },
    renderList() {
        this.showChildView(
            'criteria',
            new CriteriaCollectionView({
                collection: this.getRootCriterion().children
            })
        );
    },
    renderAddButton() {
        const model = new ButtonModel({
            label: 'Nouveau critère',
            css: 'btn icon',
            icon: 'plus',
            event: 'add:click'
        });
        const view = new ButtonWidget({
            model: model
        });
        this.showChildView('criteria', view);
    },
    onRender() {
        this.showChildView(
            'editButton',
            new ButtonWidget({
                model: new ButtonModel({
                    'label': 'edit',
                    'showLabel': false,
                    'css': 'btn icon only unstyled',
                    'icon': 'pen',
                    event: 'edit:entry:click'
                })
            })
        );
        if (this.getRootCriterion().children.length > 0) {
            this.renderList();
        } else {
            this.renderAddButton();
        }
    }
});
export default EntryFormComponent